//流要求掌握思想不用手写
const EventEmitter = require('events');
const fs = require('fs');
const { Stream } = require('node:stream');

class WriteStream extends EventEmitter(){
    constructor(){
        super();
        this.cache = [];
        this.writing = false;//用于标识是否是第一次写入
    }
    //先写入成功后
    clearBuffer() {
        let data = this.cache.shift();
        if (data) {
            this.write(data.chunk, data.encoding, data.cb);
        }else{
            this.writing = false;
            if(this.needDrain){
                this.needDrain = false;
                this.emit('drain');
            }
        }
    }
    //切片编程 AOP
    write(chunk,encoding=this.encoding,cb=()=>{}){
        
        cb = () =>{
            userCb();
            this.clearBuffer();//清空缓存逻辑
        }

        if(!this.writing){
            //当前没有正在写入说明是第一次
            //需要真正执行写入的操作
            this.writing = true
            console.log('真正写入');
        }else{
            console.log("保存到缓存区");
            this.cache.push({
                chunk,
                encoding,
                cb
            })
        }
    }

    _write(chunk,encoding,cd){
        if(typeof this.fd !== 'number'){

        }
    }
} 

//vue里边的事件调度
//自己实现一个事件环的基础模型，微前端中的singleSpa,就是一个事件模型